package com.hxut.controller;



import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hxut.common.lang.Const;
import com.hxut.common.lang.Result;
import com.hxut.entity.SysRole;
import com.hxut.entity.SysRoleMenu;
import com.hxut.entity.SysUserRole;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author MR.S
 * @since 2022-06-21
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends BaseController {

    /**
     * @description:  编辑
     * @param id
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/12 9:24
    */
    @PreAuthorize("hasAuthority('sys:role:list')")
    @GetMapping("/info/{id}")
    public Result info(@PathVariable Long id){
        SysRole sysRole = sysRoleService.getById(id);

        //获取相关联的菜单id
        List<SysRoleMenu> roleMenus = sysRoleMenuService.list(new QueryWrapper<SysRoleMenu>().eq("role_id", id));
        List<Long> menuIds=roleMenus.stream().map(roleMenu->roleMenu.getMenuId()).collect(Collectors.toList());

        sysRole.setMenuIds(menuIds);
        return Result.success(sysRole);
    }


    /**
     * @description:  分页
     * @param name
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/12 9:25
    */
    @PreAuthorize("hasAuthority('sys:role:list')")
    @GetMapping("/list")
    public Result list(String name){
        Page<SysRole> page = sysRoleService.page(getPage(), new QueryWrapper<SysRole>()
                .like(StrUtil.isNotBlank(name), "name", name));
        return Result.success(page);
    }

    /**
     * @description:  新增
     * @param sysRole
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/12 9:25
    */
    @PreAuthorize("hasAuthority('sys:role:save')")
    @PostMapping("/save")
    public Result save(@RequestBody SysRole sysRole){

        sysRole.setCreated(LocalDateTime.now());
        sysRole.setStatu(Const.STATE_ON);
        sysRoleService.save(sysRole);
        return Result.success(sysRole);
    }

    /**
     * @description:  修改
     * @param sysRole
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/12 9:25
    */
    @Transactional
    @PostMapping("/update")
    @PreAuthorize("hasAuthority('sys:role:update')")
    public Result update(@RequestBody SysRole sysRole){
        sysRole.setUpdated(LocalDateTime.now());
        sysRoleService.updateById(sysRole);

        //当更新角色信息时，清空缓存
        sysUserService.clearUserAuthorityInfoByRoleId(sysRole.getId());

        return Result.success(sysRole);
    }


    /**
     * @description:  批量删除
     * @param ids
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/12 9:26
    */
    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('sys:role:delete')")
    public Result delete(@RequestBody Long[] ids){

       sysRoleService.removeByIds(Arrays.asList(ids));

       //删除所有与角色相关的中间表
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().in("role_id",ids));
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("role_id",ids));

        //同步删除缓存
        Arrays.stream(ids).forEach(id->{
            sysUserService.clearUserAuthorityInfoByRoleId(id);
        });
        return Result.success("删除成功");
    }

    /**
     * @description:  分配权限
     * @param roleId
     * @param menuIds
     * @return: com.hxut.common.lang.Result
     * @author: MR.孙
     * @date: 2022/7/12 9:26
    */
    @Transactional
    @PostMapping("/perm/{roleId}")
    @PreAuthorize("hasAuthority('sys:role:perm')")
    public Result perm(@PathVariable Long roleId,@RequestBody Long[] menuIds){

        List<SysRoleMenu> sysRoleMenus =new ArrayList<>();
        Arrays.stream(menuIds).forEach(menuId->{
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(roleId);
            sysRoleMenu.setMenuId(menuId);

            sysRoleMenus.add(sysRoleMenu);
        });


        //先删除原来的记录，在保存新的权限
        sysRoleMenuService.remove(new QueryWrapper<SysRoleMenu>().eq("role_id",roleId));
        sysRoleMenuService.saveBatch(sysRoleMenus);
        return Result.success(menuIds);
    }

}
